package com.gzyj.jtt808.v2019;

import com.gzyj.jtt808.utils.HexBytesUtil;
import com.gzyj.jtt808.v2019.enums.BusinessDataType;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lhj
 */

@Slf4j
public class IPackageDecodeAdapter implements PackageDecodeAdapter {
    private Package aPackage;

    @Override
    public Package decode(ByteBuf in) {
        String hex = ByteBufUtil.hexDump(in);
        String tt=hex.substring(hex.indexOf("7e") + 2, hex.lastIndexOf("7e"));

        in = HexBytesUtil.readZy(tt);//转义处理

        int startFlag = Byte.toUnsignedInt(in.readByte());

        Integer xyId=in.readUnsignedShort();
        BusinessDataType businessType = BusinessDataType.find(xyId);

        try {
            if(businessType!=null){
                this.aPackage = (Package) Class.forName(businessType.getClazz()).newInstance();
                this.aPackage.decode(Unpooled.copiedBuffer(HexBytesUtil.hexTobytes(hex)));
            }else{
                log.error("暂不支持此协议 {}",Integer.toHexString(xyId));
            }


        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        return this.aPackage;
    }
}
